import axios from 'axios';
import router from '../router'
import { Message } from 'element-ui'

// 全局配置
axios.defaults.baseURL = 'http://192.168.1.3:8000/api/';
axios.defaults.timeout = 10000;

const debug = false
// 请求拦截器
axios.interceptors.request.use((config) => {
  const { token } = localStorage;
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
}, (error) => {
  if (debug) {
    if (error.request) console.log(error.request);
    else console.log('Error', error.message);
  }
  return Promise.reject(error);
});

// 响应拦截器
axios.interceptors.response.use((response) => {
  const { access_token } = response.data;
  if (access_token) localStorage.token = access_token;
  return response;
}, (error) => {
  if (error.response) {
    if(debug){
    console.log(`error.response.data:${JSON.stringify(error.response.data)}`);
    console.log(`error.response.status:${error.response.status}`);
    console.log(`error.response.headers:${JSON.stringify(error.response.headers)}`);}
    switch (error.response.status) {
      case 404: {
        router.push({ name: '404' })
        break
      }
      case 403: {
        Message({
          showClose: true,
          message: '你没有权限执行该动作',
          type: 'error'
        })
        break
      }
      case 401: {
        router.push({ name: 'Auth', params: { msg: '请先登录或注册' } })
        break
      }
      case 400: {
        Message({
          showClose: true,
          message: error.response.data.error ? error.response.data.error : error.response.data,
          type: 'error'
        })
        break
      }
      case 500: {
        router.push({ name: '500' })
        break
      }
    }
  }
  return Promise.reject(error);
});

export default axios;
